package cn.edu.sdjzu.xg21.dao;

import cn.edu.sdjzu.xg21.domain.Department;
import cn.edu.sdjzu.xg21.domain.School;
import cn.edu.sdjzu.xg21.exception.BysjException;
import cn.edu.sdjzu.xg21.service.SchoolService;
import cn.edu.sdjzu.xg21.util.JdbcHelper;

import java.sql.*;

public class DepartmentDao {
    private DepartmentDao(){}
    private static DepartmentDao departmentDao = null;
    // 返回本类的唯一对象
    public static DepartmentDao getInstance(){
        // 静态变量departmentDao为null时，才创建departmentDao对象
        // 第二次或者后来调用本方法departmentDao就不为null了，故不再创建对象
        if(departmentDao == null){
            departmentDao= new DepartmentDao();
        }
        return departmentDao;
    }

    public Department find(int id) throws SQLException, BysjException {
        Department department = null;
        Connection connection = JdbcHelper.getConn();
        Statement stmt = connection.createStatement();
        ResultSet resultSet = stmt.executeQuery("select * from department");
        while(resultSet.next()){
            if (resultSet.getInt("id") == id){
                int objectId = resultSet.getInt("id");
                String description = resultSet.getString("description");
                String no = resultSet.getString("no");
                School school = SchoolService.getInstance().find(resultSet.getInt("school"));
                department = new Department(objectId,description,no,school);
            }
        }
        JdbcHelper.close(stmt,connection);
        return department;
    }
}
